/*
 * Copyright (C) 2009 Rafael Fernandes
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.phonebooksharing.android.async;

import java.util.ArrayList;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.text.TextUtils;

import com.phonebooksharing.android.provider.PhonebookSharing.Dashboard;
import com.phonebooksharing.android.util.CloseableUtil;
import com.phonebooksharing.android.util.Global;
import com.phonebooksharing.android.util.NetworkHandlerTask;
import com.phonebooksharing.dto.gallery.ImageGalleryItem;

public class MediaStoreImageScannerTask extends NetworkHandlerTask<Context, ArrayList<ImageGalleryItem>, Void> {
    @SuppressWarnings("unchecked")
    @Override
    public Void doInBackground(Context... params) {
        final Context cx = params[0];
        try {
            ContentResolver cr = cx.getContentResolver();
            Cursor c = null;
            try {
                String url = String.format(Global.IMAGE_SERVLET_URL, "p" /*ac*/, "a" /*q*/, "" /*c*/, "" /*p*/, "" /*ps*/, "" /*mt*/, "" /*w*/, "" /*h*/);
                ArrayList<Integer> serverList = (ArrayList<Integer>)doNetworkPost(url, Global.authItem);
                
                c = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, 
                                new String[]{Images.Media._ID, Images.Media.DATE_ADDED, Images.Media.TITLE,
                                             Images.Media.LATITUDE, Images.Media.LONGITUDE, Images.Media.DATA,
                                             Images.Media.MIME_TYPE}, null, null, null);

                if(c != null && c.moveToFirst()) {
                    int id;
                    ArrayList<ImageGalleryItem> list = new ArrayList<ImageGalleryItem>();
                    ImageGalleryItem ig;
                    do {
                        id = c.getInt(0);
                        if(!serverList.contains(id)) {//should be new
                            ig = new ImageGalleryItem();
                            ig.title = c.getString(2);
                            if(TextUtils.isEmpty(ig.title)) {
                                ig.title = "<no title>";
                            }
                            
                            ig.imageLatitude = c.getString(3);
                            ig.imageLongitude = c.getString(4);
                            ig.when = c.getLong(1);
                            ig.deviceID = c.getInt(0);
                            ig.photoID = ig.deviceID;
                            ig.photoUri = Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, c.getString(0)).toString();
                            ig.devicePath = c.getString(5);
                            ig.mimeType = c.getString(6);
                            list.add(ig);
                        }
                    } while (c.moveToNext());

                    ContentValues cv = new ContentValues();
                    cv.put(Dashboard.QTY_NON_SHARING_IMAGES, c.getCount());
                    cr.update(Dashboard.CONTENT_URI, cv, null, null);
                    
                    publishProgress(list);
                }
            } finally {
                CloseableUtil.safeClose(c);
                c = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            cancel(true);
        }
        return null;
    }

    @Override
    public void onPostExecute(Void aVoid) {
        // pref = null;
    }
}
